package com.shop.myweb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.myweb.common.R;
import com.shop.myweb.entity.DTO.GoodsDTO;
import com.shop.myweb.entity.Goods;
import com.shop.myweb.service.GoodsService;
import com.shop.myweb.utils.ListToPage;
import com.shop.myweb.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: ZhuangShuo
 * @date: 2023/4/25 10:03
 * @description:
 */
@RestController
@Slf4j
@RequestMapping("/goods")
public class GoodsController {


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增商品
     *
     * @return
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody GoodsDTO goodsDTO) {
        Goods goods = goodsDTO.getGoods();
        int page = goodsDTO.getPage();
        int pageSize = goodsDTO.getPageSize();
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        goodsService.save(goods);

        return R.success("新增商品成功");
    }


    @GetMapping("/list")
    public R<List<Goods>> list() {
        log.info("查询列表");

        List<Goods> list = goodsService.selectRandomList();

        return R.success(list);
    }

    @GetMapping("/search")
    public R<Page> search(String keyword, Integer page, Integer pageSize) {


        Page<Goods> pageInfo = new Page<>(page, pageSize);

        if (StringUtils.isEmpty(keyword)) {
            return R.error("搜索不能为空");
        }

        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_searchKeyword_" + keyword + "_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) != null) {
                pageInfo = (Page<Goods>) redisTemplate.opsForValue().get(key);
                return R.success(pageInfo);
            }
            //条件构造器
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            //添加过滤条件
            queryWrapper.and(
                    wrapper ->
                            wrapper.like("name", keyword).or().like("description", keyword)
            );
            //执行分页查询
            goodsService.page(pageInfo, queryWrapper);
            redisTemplate.opsForValue().set(key, pageInfo, 60, TimeUnit.SECONDS);
        } else {
            //条件构造器
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            //添加过滤条件
            queryWrapper.and(
                    wrapper ->
                            wrapper.like("name", keyword).or().like("description", keyword)
            );
            //执行分页查询
            goodsService.page(pageInfo, queryWrapper);
        }
        if (pageInfo.getTotal() == 0)
            return R.error("无数据");
        return R.success(pageInfo);
    }

    /**
     * 商品信息分页查询
     *
     * @param page     第多少页
     * @param pageSize 页面大小
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {

        //构造分页构造器对象
        Page<Goods> pageInfo = new Page<>(page, pageSize);

        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) != null) {
                pageInfo = (Page<Goods>) redisTemplate.opsForValue().get(key);
                return R.success(pageInfo);
            }
            //条件构造器
            LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
            //添加排序条件
            queryWrapper.orderByDesc(Goods::getSort);
            //执行分页查询
            goodsService.page(pageInfo, queryWrapper);
            redisTemplate.opsForValue().set(key, pageInfo, 60, TimeUnit.SECONDS);
        } else {
            //条件构造器
            LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
            //添加排序条件
            queryWrapper.orderByDesc(Goods::getSort);
            //执行分页查询
            goodsService.page(pageInfo, queryWrapper);
        }


        return R.success(pageInfo);
    }


    /**
     * 根据id查询商品信息
     *
     * @param id 商品id
     * @return
     */
    @GetMapping("/{id}")
    public R<Goods> get(@PathVariable Long id) {
        Goods goods;
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goods_" + id;
            goods = (Goods) redisTemplate.opsForValue().get(key);
            if (goods == null) {
                goods = goodsService.getById(id);
                redisTemplate.opsForValue().set(key, goods, 60, TimeUnit.SECONDS);
            }
        } else {
            goods = goodsService.getById(id);
        }
        return R.success(goods);
    }
//// /dish/status/${params.status}
//    @PostMapping("/status/${params.status}")
//    public R<String> changeGoodsStatus()

    @PutMapping("/edit")
    public R<String> update(@RequestBody GoodsDTO goodsDTO) {
        log.info("修改商品信息");
        Goods goods = goodsDTO.getGoods();
        int page = goodsDTO.getPage();
        int pageSize = goodsDTO.getPageSize();
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        goodsService.updateById(goods);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long id, Integer page, Integer pageSize) {
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        goodsService.removeById(id);
        return R.success("删除成功");
    }

    @PutMapping("/status")
    public R<String> updateStatus(Long id, Integer page, Integer pageSize) {
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "goodsPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        Goods goods = goodsService.getById(id);
        if (goods.getStatus() == 1)
            goods.setStatus(0);
        else
            goods.setStatus(1);
        goodsService.updateById(goods);
        return R.success("修改成功");
    }


    @GetMapping("/indexList")
    public R<Page> indexList() {
        List<Goods> list = goodsService.selectIndexRandomPage();
        Page<Goods> tPage = ListToPage.listToPage(1, 4, list);
        return R.success(tPage);

    }
}